package com.cheyun.netsalev3.viewmodel

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.DatePicker
import android.widget.TimePicker
import androidx.annotation.MainThread
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.MyApplication
import com.cheyun.netsalev3.bean.*
import com.cheyun.netsalev3.bean.basedata.BaseDataParam
import com.cheyun.netsalev3.bean.dms.DmsUserAuth
import com.cheyun.netsalev3.bean.order.OrderChooseData
import com.cheyun.netsalev3.repository.ClueFollowUpRepository
import com.cheyun.netsalev3.utils.CheckIdCard
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.view.ChoiceCustomerActivity
import com.cheyun.netsalev3.view.choosecar.ChooseCarActivity
import com.cheyun.netsalev3.view.choosecity.ChooseCityActivity
import com.cheyun.netsalev3.view.cluefollowup.ClueFollowUpActivity
import com.cheyun.netsalev3.view.mars.choosecar.MarsChooseCarActivity
import com.cheyun.netsalev3.view.orderlist.ChoiceOrderActivity
import com.cheyun.netsalev3.widget.DatePickerFragment
import com.cheyun.netsalev3.widget.MyDialog
import com.cheyun.netsalev3.widget.TimePickerFragment
import com.dou361.dialogui.DialogUIUtils
import com.dou361.dialogui.listener.DialogUIListener
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import java.io.Serializable
import java.util.*
import kotlin.collections.HashMap

class ClueFollowUpActivityViewModel(var data: ClueDetails, var leve: String,
                                    var repository: ClueFollowUpRepository,var come:String,
                                    var keliudata:Data?,var isNew:Boolean,var waitAddData:EditClueParam,
                                    var levelLock:Boolean,var canceldrive:Int) : BaseViewModel() {

    //是否开启库存模块 1开启 0 未开启
    var statkun = 0
    //当前选中Fragment位置
    var viewPagerPos = 0
    var PagerPos = MutableLiveData<Int>()

    //是否确认修改试驾时间 0=> 否 1=>是
    var isdrivetime = 0

    init {
        PagerPos.postValue(viewPagerPos)
    }

    //订车底部按钮显示
    var bottom1 = ObservableField<String>("完成")

    //订车头部显示
    var top1 = MutableLiveData<String>()
    //点击位置
    var position = 0
    var activity: AppCompatActivity? = null

    //年月日
    var year = ""
    var month = ""
    var day = ""
    //下次跟进时间距离当前时间天数
    var alarmday = 0
    var baseData = MySharedPreferences.getBaseData()

    var operComplete = MutableLiveData<Boolean>()

    var state = ""
    //订车提车同一窗口
    var od = false

    var cert_images:ArrayList<String> = arrayListOf()

    var yudingdanData:OrderChooseData? = null

    //点击头部返回
    fun clickLeft(view: View?) {
        if (viewPagerPos > 0) {
            when (viewPagerPos) {
                //退库申请
                3 -> {
                    viewPagerPos = 0
                    PagerPos.postValue(viewPagerPos)
                }
                //订车
                1 -> {
                    viewPagerPos = 0
                    PagerPos.postValue(viewPagerPos)
                }
                //提车
                2 -> {
                    //直接提车
                    if ((data.Level == "D" && state == "D") || od) {
                        viewPagerPos = 0
                        PagerPos.postValue(viewPagerPos)
                    } else {
                        viewPagerPos = 1
                        PagerPos.postValue(viewPagerPos)
                    }
                }
               //提车订车一体
                4-> {
                    viewPagerPos = 0
                    PagerPos.postValue(viewPagerPos)
                }
            }

        } else {
            view?.context?.apply {
                if (this is AppCompatActivity) {
                    this.finish()
                }
            }
        }
    }

    /**
     * 库存按钮
     */
    var stockBtnEnable = MutableLiveData<Boolean>()
    fun clickButWaitStock(view: View) {
        var fail: () -> Unit = {
            stockBtnEnable.postValue(true)
        }
        view.isEnabled = false
        repository.editClue(initData(), this::onSuccess,fail)
    }

    /**
     * 提车按钮
     */
    var buyBtnEnable = MutableLiveData<Boolean>()
    fun clickButLiftCar(view: View) {
        if (Liftcar[0].value.isNullOrBlank() || Liftcar[0].value <= "0") {
            MyToast("请选择提车时间")
            return
        }
        if (Liftcar[4].value.isNullOrBlank()) {
            MyToast("请选择购买类型")
            return
        }
        var fail: () -> Unit = {
            buyBtnEnable.postValue(true)
        }
        //请求数据
        view.isEnabled = false
        //2020-04-22 添加线索-->直接跟进一步完成
        if(isNew){
//            var moth: (clueDetails: ClueDetails) -> Unit = {
//                data.tid = it.tid
//                data.uname = it.uname
//                data.phone = it.phone
//                data.sex = it.sex
//                data.infotype = it.infotype
//                data.infoplace = it.infoplace
//                data.infosource = it.infosource
//                repository.editClue(initDataLiftCar(), this::onSuccess,fail)
//            }
//            var fail: () -> Unit = {
//                buyBtnEnable.postValue(true)
//            }
//            repository.addClue(waitAddData, moth,fail)
            setWaitData()
        }
        repository.editClue(initDataLiftCar(), this::onSuccess,fail)

    }

    /**
     * 提车订车一体按钮
     */
    var bookingBuyBtnEnable = MutableLiveData<Boolean>()
    fun clickButBookingLiftCar(view: View) {
        if (BookingLiftcar[0].value.isNullOrBlank() || BookingLiftcar[0].value <= "0") {
            MyToast("请选择签约时间")
            return
        }
        if (BookingLiftcar[1].value.isNullOrBlank() || BookingLiftcar[1].value <= "0") {
            MyToast("请选择提车时间")
            return
        }
        if (BookingLiftcar[2].value.isNullOrBlank() ) {
            MyToast("请选择提车品牌车系")
            return
        }
        if (BookingLiftcar[3].value.isNullOrBlank()) {
            MyToast("请选择提车车辆颜色")
            return
        }
        if (BookingLiftcar[4].value.isNullOrBlank()) {
            MyToast("请选择提车内饰颜色")
            return
        }
        if (BookingLiftcar[5].value.isNullOrBlank()) {
            MyToast("请选择付款方式")
            return
        }
        if (BookingLiftcar[8].id.isNullOrBlank()) {
            MyToast("请输入预订价格")
            return
        }
        if (!BookingLiftcar[5].value.isNullOrBlank() && BookingLiftcar[5].ikey == "loan") {
            if (BookingLiftcar[6].value.isNullOrBlank()) {
                MyToast("请选择按揭银行")
                return
            }
            if (BookingLiftcar[7].id.isNullOrBlank()) {
                MyToast("请输入按揭服务费")
                return
            }
        }
        if (BookingLiftcar[14].value.isNullOrBlank()) {
            MyToast("请选择购买类型")
            return
        }
        var fail: () -> Unit = {
            bookingBuyBtnEnable.postValue(true)
        }
        //请求数据
        view.isEnabled = false

        //2020-04-22 添加线索-->直接跟进一步完成
        if(isNew){
//            var moth: (clueDetails: ClueDetails) -> Unit = {
//                data.tid = it.tid
//                data.uname = it.uname
//                data.phone = it.phone
//                data.sex = it.sex
//                data.infotype = it.infotype
//                data.infoplace = it.infoplace
//                data.infosource = it.infosource
//                repository.editClue(initDataBookingLiftCar(), this::onSuccess,fail)
//            }
//            var fail: () -> Unit = {
//                bookingBuyBtnEnable.postValue(true)
//            }
//            repository.addClue(waitAddData, moth,fail)

            setWaitData()
        }
        repository.editClue(initDataBookingLiftCar(), this::onSuccess,fail)
    }

    @MainThread
    fun onSuccess(clueDetails: ClueDetails):Unit {
        LiveEventBus.get().with("CustomerItemFragment").postValue("CustomerItemFragment")
        var activitys = MyApplication.getInstance().getAcitvitys()
        for (activity in activitys) {
            if (activity is ClueFollowUpActivity ) {
                activity.finish()
            }
        }
        LiveEventBus.get().with("clueupdatge").postValue("")
        if(isNew){
            this.data.tid = clueDetails.tid
            operComplete.postValue(true)
        }
        when (viewPagerPos) {
            3 -> {
                MyToast("申请成功")
            }
            //提车
            2 -> {
                MyToast("提交成功")
            }
            4 -> {
                MyToast("提交成功")
            }
            else -> {
                if(canceldrive == 1){
                    MyToast("取消预约成功")
                }else{
                    if(isdrivetime == 1){
                        MyToast("试驾时间修改成功")
                    }else {
                        MyToast("跟进成功")
                    }
                }
            }
        }
    }

    var bookingBtnEnable = MutableLiveData<Boolean>()
    /**
     * 订车底部按钮
     */
    fun clickButBooking(view: View) {
        if (booking[0].value.isNullOrBlank()) {
            MyToast("请选择预定车系")
            return
        }
        if (booking[1].value.isNullOrBlank() && booking[1].spec_select == 1) {
            MyToast("请选择预定车型")
            return
        }
        if (booking[2].value.isNullOrBlank()  && booking[1].spec_select == 1) {
            MyToast("请选择预定产品")
            return
        }
//        if (booking[3].value.isNullOrBlank()) {
//            MyToast("请选择订车辆颜色")
//            return
//        }
//        if (booking[4].value.isNullOrBlank()) {
//            MyToast("请选择预订内饰颜色")
//            return
//        }
        if (booking[6].value.isNullOrBlank()) {
            MyToast("请选择证件类型")
            return
        }
        if (booking[7].id.isNullOrBlank()) {
            MyToast("请输入证件号码")
            return
        }
        if(booking[6].id.equals("1")){
            //身份证验证
            if(!CheckIdCard.check(booking[7].id)){
                MyToast("请入正确的身份证号")
                return
            }
        }
        if (booking[8].id.isNullOrBlank()) {
            MyToast("请输入生日")
            return
        }
        if (booking[10].id.isNullOrBlank()) {
            MyToast("请输入预订价格")
            return
        }
        if (booking[11].value.isNullOrBlank()) {
            MyToast("请选择客户类型")
            return
        }
        if (booking[12].value.isNullOrBlank()) {
            MyToast("请选择购买类型")
            return
        }
        if (booking[13].value.isNullOrBlank()) {
            MyToast("请选择地区")
            return
        }
        if (booking[14].id.isNullOrBlank()) {
            MyToast("请输入详细地址")
            return
        }

        var fail: () -> Unit = {
            bookingBtnEnable.postValue(true)
        }
        //请求数据
        view.isEnabled = false
        //2020-04-22 添加线索-->直接跟进一步完成
        if(isNew){
            setWaitData()
        }
        repository.editClue(initDataBooking(), this::onSuccess,fail)
    }

    /**
     * 封装请求订车数据
     */
    private fun initDataBooking(): HashMap<String, String> {
        var hashMap = initData()
        for (item in booking) {
            if (item.show) {
                hashMap[item.idname] = item.id
            }
        }
        hashMap.put("ibrandgrou",hashMap.get("iseries")!!+","+hashMap.get("ispec")!!+","+hashMap.get("iproduct")!!)
        hashMap.set("strikeexterior","0")
        hashMap.set("strikeinterior","0")
//        if(cert_images.size>0){
//            hashMap.put("cert_image_url",cert_images.joinToString(","));
//        }
        return hashMap
    }

    /**
     * 封装请求提车数据
     */
    private fun initDataLiftCar(): HashMap<String, String> {
        var hashMap = initDataBooking()
        for (item in Liftcar) {
            if (item.show) {
                hashMap[item.idname] = item.id
            }
        }
        hashMap.put("dbrandgrou",hashMap.get("dbrandgroup")!!)
        hashMap.put("ibrandgrou",hashMap.get("ibrandgroup")!!)
        return hashMap
    }

    /**
     * 封装请求订车数据
     */
    private fun initDataBookingLiftCar(): HashMap<String, String> {
        var hashMap = initDataBooking()
        for (item in BookingLiftcar) {
            if (item.show) {
                hashMap[item.idname] = item.id
            }
        }
        hashMap.put("dbrandgrou",hashMap.get("dbrandgroup")!!)
        hashMap.put("ibrandgrou",hashMap.get("dbrandgroup")!!)
        hashMap.put("ibrandgroup",hashMap.get("dbrandgroup")!!)
        hashMap.put("strikeexterior",hashMap.get("deliverexterior")!!)
        hashMap.put("strikeinterior",hashMap.get("deliverinterior")!!)

        return hashMap
    }

    init {
        top1.postValue("订车")
        MySharedPreferences.getLoginData()?.channel?.settings?.storage?.state?.apply {
            statkun = this
        }
    }

    var followBtnEnable = MutableLiveData<Boolean>()
    /**
     * 点击底部按钮
     */
    fun clickBut(view: View) {
//        KeyValueParam("有效性:", youxiaoPop.toList(), "effective"),0
//        KeyValueParam("跟进时间:", 1, "followtime", value = time, id = time),1
//        KeyValueParam("本次跟进方式:", genjinpoplist, "connectway"),2
//        KeyValueParam("到店时间:", 1, "arrivetime"),3
//        KeyValueParam("离店时间:", 1, "leavetime"),4
//        KeyValueParam("到店人数:", 2, "arrivepeoplenum"),5
//        KeyValueParam("本次报价:", 2, "followprice"),6
//        KeyValueParam("跟进情况:", 3, "followinfo"),7
//        KeyValueParam("到店客户:", 1, "rcvid"),8
//        KeyValueParam("是否试驾:", sijialist, "driving"),9
//        KeyValueParam("无效原因:", invalidlist, "invalid"),10
//        KeyValueParam("跟进级别:", levelList, "customerlevel"),11
//        KeyValueParam("下次跟进人:", memberist, "owneruid"),12
//        KeyValueParam("下次跟进时间:", 1, "remindetime"),13
//        KeyValueParam("下次跟进方式:", genjinpoplist, "ncway"),14
//        KeyValueParam("下次到店事项:", storeitemslist, "storeitems"),15
//        KeyValueParam("战败原因:", giveupcauselist, "giveupcause"),16
//        KeyValueParam("战败原因分析:", 2, "failurereason", 2)17

//        跟进时必填字段 【跟进时间；本次跟进方式；跟进情况；跟进级别；下次跟进时间；下次跟进方式】
        if (defaultViewData[0].value.isNullOrBlank()) {
            MyToast("请选择有效性")
            return
        }
        if (defaultViewData[2].value.isNullOrBlank()) {
            MyToast("请选择跟进方式")
            return
        }
        if (defaultViewData[2].value == "到店") {
            //展督模式下需要选择到店客户
            if(MySharedPreferences.getLoginData()?.channel?.settings?.receive == 0) {
                if (defaultViewData[8].value.isNullOrBlank()) {
                    MyToast("请选择到店客户")
                    return
                }
            }else{
                //无展督模式下不需要选择到店客户， 需要选择到店时间、离店时间、到店人数
                if (defaultViewData[3].value.isNullOrBlank()) {
                    MyToast("请选择到店时间")
                    return
                }
                if (defaultViewData[4].value.isNullOrBlank()) {
                    MyToast("请选择离店时间")
                    return
                }
                if (defaultViewData[5].id.isNullOrBlank()) {
                    MyToast("请输入到店人数")
                    return
                }
            }
        }

        if (defaultViewData[7].id.isNullOrBlank()) {
            MyToast("请输入跟进情况")
            return
        }
        var checkCar = true
        //线索有效性为无效 ， 不判断跟进级别
        if(!defaultViewData[0].id.equals("2")){
            if (defaultViewData[11].value.isNullOrBlank()) {
                MyToast("请选择跟进级别")
                return
            }
        }else{
            if (defaultViewData[10].value.isNullOrBlank()) {
                MyToast("请选择无效原因")
                return
            }
            checkCar = false
        }

        //跟进以及基础数据中的追踪报警时间：天数为0则下次跟进时间、下次跟进方式非必填，非0则必填。若选择其中一项，则另一项也必填，D-》D为特殊情况，不受报警时间影响，为非必填。非必填选项均不填入默认值。
        //O\D追踪报警时间非0,时   N,H,A,B,C 到O   \    O到D应当为必填且有默认值。
        var isMust = true;
        if(defaultViewData[11].ikey.equals("F")){
            isMust = false
        }else{
            if(defaultViewData[11].ikey.equals("D")|| defaultViewData[11].ikey.equals("O")){
                for(l in this.data.levelList){
                    if(l.ikey.equals(defaultViewData[11].value)){
                        if(l.settings.alarmday == 0){
                            isMust = false
                        }
                    }
                }
                if(isMust){
                    if(defaultViewData[11].value.equals("D") && this.data.Level.equals("D")){
                        isMust = false
                    }
                }
            }
        }
        if(defaultViewData[0].id.equals("2")){
            isMust = false
        }
        if(isMust){
            if (defaultViewData[13].value.isNullOrBlank()) {
                MyToast("请选择下次跟进时间")
                return
            }
            if (defaultViewData[14].value.isNullOrBlank()) {
                MyToast("请选择下次跟进方式")
                return
            }
        }

//        if(defaultViewData[13].value.isNullOrBlank() && !defaultViewData[14].value.isNullOrBlank()){
//            MyToast("请选择下次跟进时间")
//            return
//        }
//        if(!defaultViewData[13].value.isNullOrBlank() && defaultViewData[14].value.isNullOrBlank()){
//            MyToast("请选择下次跟进方式")
//            return
//        }
        if (defaultViewData[14].ikey == "arrive") {
            if(defaultViewData[15].value.isNullOrEmpty()){
                MyToast("请选择下次到店事项")
                return
            }
        }
        if (statkun == 1 && data.vin == "" && state == "D" && !data.Level.equals("D")) {
            MyToast("请等待分配库存")
            return
        }
        if (state == "O" && statkun == 1 && data.Level == "D" && data.is_out == "1") {
            viewPagerPos = 3
            PagerPos.postValue(3)
//            MyToast( "退库申请")
            return
        }

        if(defaultViewData[11].ikey.equals("F")){
            if (defaultViewData[16].value.isNullOrBlank()) {
                MyToast("请选择战败原因")
                return
            }
            if (defaultViewData[17].id.isNullOrBlank()) {
                MyToast("请输入战败原因分析")
                return
            }
        }

        if(checkCar) {
            if (defaultViewData[20].value.isNullOrBlank()) {

                MyToast("请选择意向车系")
                return
            }
            if (defaultViewData[21].value.isNullOrBlank() && defaultViewData[21].spec_select == 1) {
                MyToast("请选择意向车型")
                return
            }
        }

        if (defaultViewData[0].id.equals("1")) {
            //有效， 联系方式必须是手机号
            if (!FunctionUtils.isPhone3(defaultViewData[22].id)) {
                MyToast("联系方式必须是手机号")
                return
            }
        }
//        if(defaultViewData[11].ikey == "O" && this.data.adorder == 1){
////            在线下定需求中, 跟进选择O级之后,如果adorder == 1 需要绑定预订单, 选择对应预订单后 需要传 预订单数据的, adorderid
//            if(defaultViewData[23].id.isNullOrEmpty()){
//                MyToast("请选择预订单")
//                return
//            }
//        }

        var content = view.context
        if (content is AppCompatActivity) {
            //订车
            when (state) {
                //订车
                "O" -> {
                    top1.postValue("订车")
                    bottom1.set("完成")
                    viewPagerPos = 1
                    PagerPos.postValue(viewPagerPos)

                }
                //提车
                "D" -> {
                    if (data.Level == "D") {
                        viewPagerPos = 2
                        PagerPos.postValue(viewPagerPos)
                    } else {
                        //先订车
//                        viewPagerPos = 1
//                        PagerPos.postValue(viewPagerPos)
//                        top1.postValue("订车信息")
//                        bottom1.set("下一步")

                        viewPagerPos = 4
                        PagerPos.postValue(viewPagerPos)
                        top1.postValue("提车补充信息")
                        bottom1.set("完成")
                    }
                }
                else -> {
                    //2020-04-22 添加线索-->直接跟进一步完成
                    if (isNew) {
                        setWaitData()
                    }
                    followClue(view)
                }
            }
        }
    }

    private var n = false
    private var dialog : Dialog? = null
    private fun followClue(view:View){
        dialog = DialogUIUtils.showLoadingVertical(view.context, "提交中...",false,false,false).show()
        var moth: (d: DmsUserAuth) -> Unit = {
            if(dialog!=null) {
                DialogUIUtils.dismiss(dialog)
            }
            Looper.prepare()
            if(it.dmsauth == 0){
                var msg = "该线索拥有者无销售顾问权限，本次操作无法推送到DMS，是否确认提交"
                if(n){
                    msg = "您没有销售顾问权限，本次操作无法推送到DMS，是否确认添加"
                }
                var dialog = DialogUIUtils.showMdAlert(view.context as Activity,"",msg ,object: DialogUIListener(){
                    override fun onNegative() {

                    }

                    override fun onPositive() {
                        confirmFollow(view)
                    }
                }).show()
                FunctionUtils.setAlertDialogPos(dialog)
            }else{
                confirmFollow(view)
            }

            Looper.loop()
        }

        var uid =  data.owneruid
        var channel = data.channel
        n = false
        if(channel.isEmpty() && uid.isEmpty()){
            //新建线索
            uid = MySharedPreferences.getLoginData()?.member?.uid.toString()
            channel = MySharedPreferences.getLoginData()?.channel?.id.toString()
            n = true
        }
        var fail: () -> Unit = {
            followBtnEnable.postValue(true)
            if(dialog!=null) {
                DialogUIUtils.dismiss(dialog)
            }
        }
        repository.checkDms(uid,channel,moth,fail)
    }

    private fun confirmFollow(view:View){
        var fail: () -> Unit = {
            followBtnEnable.postValue(true)
            if(dialog!=null) {
                DialogUIUtils.dismiss(dialog)
            }
        }
//        view.isEnabled = false
        repository.editClue(initData(), this::onSuccess,fail)
    }

    /**
     * 封装请求数据
     */
    private fun initData(): HashMap<String, String> {
        var map = HashMap<String, String>()
        map["nkey"] = "archive.purge"
        map["uname"] = data.uname
        map["phone"] = data.phone
        map["sex"] = data.sex.toString()
        map["tid"] = data.tid.toString()
        map["infotype"] = data.infotype
        map["infoplace"] = data.infoplace
        map["infosource"] = data.infosource
        if(isNew){
            var json = Gson().toJson(waitAddData)
            var  map2 = Gson().fromJson(json, HashMap<String, String>()::class.java)
            map.putAll(map2)
        }
        for (item in defaultViewData) {
            if (item.show) {
                map[item.idname] = item.id
            }
        }

        //2021-02-25 有试驾记录的调用线索编辑功能
        if(!this.data.reserveid.equals("0") && this.data.reserveid.isNotEmpty()) {
            map["reserveid"] = data.reserveid
            map["canceldrive"] = canceldrive.toString()
            map["isdrivetime"] = isdrivetime.toString()
        }

        if(map.containsKey("tracktag_online") || map.containsKey("tracktag_offline")){
            map["tracktag"] =  map["tracktag_online"]+","+map["tracktag_offline"]
        }
        if(map["tracktag_online"]!!.isEmpty() && map["tracktag_offline"]!!.isEmpty()){
            map["tracktag"] = data.tracktag.joinToString(",")
        }

        Log.e("param", map.toString())
        return map
    }

    private fun setWaitData(){
        data.uname = waitAddData.uname
        data.phone = waitAddData.phone
        data.sex = waitAddData.sex.toInt()
        data.infotype = waitAddData.infotype
        data.infoplace = waitAddData.infoplace
        data.infosource = waitAddData.infosource
    }

    var bottom = ObservableField<String>("完成")
    //0：继续跟进；1：有效；2：无效
    private var youxiaoPop = arrayOf(
            DialogParam("待判定", "0"),
            DialogParam("有效", "1"),
            DialogParam("无效", "2")
    )
    //viewdata
    private var defaultViewData: Array<KeyValueParam>


//    "线上活动标签:",
//    "线下活动标签:"
    //默认
    var morenpop = arrayOf(
            "有效性:",
            "跟进时间:",
            "本次跟进方式:",
            "本次报价:",
            "跟进情况:"
    )
    //  继续跟进有效
    var youxiaoPos = arrayOf(
            "有效性:",
            "跟进时间:",
            "本次跟进方式:",
            "本次报价:",
            "跟进情况:",
            "跟进级别:",
            "下次跟进时间:",
            "下次跟进方式:",

            "线上活动标签:",
            "线下活动标签:",

            "意向车系:",
            "意向车型:",

            "联系电话:"
    )
    //无效
    var wuxiaoPos = arrayOf(
            "有效性:",
            "跟进时间:",
            "本次跟进方式:",
            "本次报价:",
            "跟进情况:",
            "无效原因:",

            "线上活动标签:",
            "线下活动标签:",

            "意向车系:",
            "意向车型:",

            "联系电话:"
    )
    // 有效-到店-战败
    var zhanbaiPop = arrayOf(
            "有效性:",
            "跟进时间:",
            "本次跟进方式:",
            "本次报价:",
            "到店客户:",
            "跟进情况:",
            "是否试驾:",
            "跟进级别:",
            "战败原因:",
            "战败原因分析:",

            "线上活动标签:",
            "线下活动标签:",

            "意向车系:",
            "意向车型:",

            "联系电话:"
    )
    // 有效-到店-其他
    var namelist = arrayOf(
            "有效性:",
            "跟进时间:",
            "本次跟进方式:",
            "本次报价:",
            "跟进情况:",

            "到店客户:",
            "是否试驾:",
            "跟进级别:",

            "下次跟进时间:",
            "下次跟进方式:",

            "线上活动标签:",
            "线下活动标签:",

            "意向车系:",
            "意向车型:",

            "联系电话:"
    )
    // 有效-其他-战败
    var zhanbaiqitaPop = arrayOf(
            "有效性:",
            "跟进时间:",
            "本次跟进方式:",
            "本次报价:",
            "跟进情况:",
            "跟进级别:",
            "战败原因:",
            "战败原因分析:",

            "线上活动标签:",
            "线下活动标签:",

            "意向车系:",
            "意向车型:",

            "联系电话:"
    )
    // 有效-其他-订车
    var dingche2 = arrayOf(
            "有效性:",
            "跟进时间:",
            "本次跟进方式:",
            "本次报价:",
            "跟进情况:",

//            "下次跟进人:",
            "跟进级别:",
            "下次跟进时间:",
            "下次跟进方式:",

            "线上活动标签:",
            "线下活动标签:",

            "意向车系:",
            "意向车型:",

            "联系电话:"
    )
    // 有效-到店-订车
    var dingche = arrayOf(
            "有效性:",
            "跟进时间:",
            "本次跟进方式:",
            "本次报价:",
            "跟进情况:",

            "到店客户:",
            "是否试驾:",
//            "下次跟进人:",
            "跟进级别:",
            "下次跟进时间:",
            "下次跟进方式:",

            "线上活动标签:",
            "线下活动标签:",

            "意向车系:",
            "意向车型:",

            "联系电话:"
    )


    //视图数据
    var viewList = MutableLiveData<List<KeyValueParam>>()

    init {
        Log.d("follow","come:"+come)
        //本次跟进方式
        var genjinpoplist = ArrayList<DialogParam>()
        baseData?.connectway?.apply {
            Liftcar
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                genjinpoplist.add(item)
            }
        }
        //跟进级别
        var levelList = ArrayList<DialogParam>()
        for (i in data.levelList) {
            if (i.ikey == "F") {
                if (data.effective == "1") {
                    var item = DialogParam(i.title, i.ikey.toString())
                    item.ikey = i.ikey
                    levelList.add(item)
                }

            } else {
                var item = DialogParam(i.title, i.ikey.toString())
                item.ikey = i.ikey
                levelList.add(item)
            }

        }
        //无效原因
        var invalidlist = ArrayList<DialogParam>()
        baseData?.invalid?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                invalidlist.add(item)
            }

        }
        //战败原因
        var giveupcauselist = ArrayList<DialogParam>()
        baseData?.giveupcause?.apply {
            for (i in this) {
                if(i.ikey.equals("cause")) continue
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                giveupcauselist.add(item)
            }

        }
        //是否试驾
        var sijialist = ArrayList<DialogParam>()

        sijialist.add(DialogParam("是", "1"))
        sijialist.add(DialogParam("否", "0"))
        //下次到店事项
        var storeitemslist = ArrayList<DialogParam>()
        baseData?.storeitems?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                storeitemslist.add(item)
            }

        }

        //下次跟进人
        var memberist = ArrayList<DialogParam>()
        baseData?.member?.apply {
            for (i in this) {
                var item = DialogParam(i.realname, i.uid.toString())
                memberist.add(item)
            }
        }

        //线上标签
        var ntags = ArrayList<DialogParam>()
        baseData?.ntags?.apply {
            for (i in this) {
                //判断活动是否在可用时间范围内, 活动是否只作显示使用
                if(i.effect == 1 && i.readonly == 0) {
                    var item = DialogParam(i.title, i.id.toString())
                    item.ikey = i.id.toString()
                    ntags.add(item)
                }
            }
        }
        //线下标签
        var mtags = ArrayList<DialogParam>()
        baseData?.mtags?.apply {
            for (i in this) {
                //判断活动是否在可用时间范围内, 活动是否只作显示使用
                if(i.effect == 1 && i.readonly == 0) {
                    var item = DialogParam(i.title, i.id.toString())
                    item.ikey = i.id.toString()
                    mtags.add(item)
                }
            }
        }

        var time = FunctionUtils.getTime()
//        跟进时必填字段 【跟进时间；本次跟进方式；跟进情况；跟进级别；下次跟进时间；下次跟进方式】
        defaultViewData = arrayOf(
                KeyValueParam("有效性:", youxiaoPop.toList(), "effective", isMust = true),  //.0
                KeyValueParam("跟进时间:", 1, "followtime", value = time, id = time, isMust = true,isEnable = false),  //1
                KeyValueParam("本次跟进方式:", genjinpoplist, "connectway", isMust = true), //2
                KeyValueParam("到店时间:", 1, "arrivetime"),//3
                KeyValueParam("离店时间:", 1, "leavetime"),//4
//                KeyValueParam("到店人数:", 2, "arrivepeoplenum"),
                KeyValueParam("到店人数:", 2, "arrpnum",0),//5
                KeyValueParam("本次报价:", 2, "followprice"),//6
                KeyValueParam("跟进情况:", 3, "followinfo", isMust = true),//7

                KeyValueParam("到店客户:", 1, "rcvid", isMust = true),//8
                KeyValueParam("是否试驾:", sijialist, "driving", value = "否", id = "0"),//9
                KeyValueParam("无效原因:", invalidlist, "invalid",isMust = true),//10
                KeyValueParam("跟进级别:", levelList, "customerlevel", isMust = true),//11
                KeyValueParam("下次跟进人:", memberist, "owneruid"),//12
                KeyValueParam("下次跟进时间:", 1, "remindetime", isMust = true),//13
                KeyValueParam("下次跟进方式:", genjinpoplist, "ncway", isMust = true),//14
                KeyValueParam("下次到店事项:", storeitemslist, "storeitems"),//15
                KeyValueParam("战败原因:", giveupcauselist, "giveupcause"),//16
                KeyValueParam("战败原因分析:", 2, "failurereason", 2),//17
//                KeyValueParam("线上活动标签:", ntags, "tracktag_online","","",true,false,true,true ), //18
//                KeyValueParam("线下活动标签:", mtags, "tracktag_offline","","",true,false,true,true), //19
                KeyValueParam("意向车系:", 1, "series", isMust = true), //20
                KeyValueParam("意向车型:", 1, "spec", isMust = true), //21

                KeyValueParam("联系电话:", 2, "phone",0)  //22
//                KeyValueParam("预订单:", 1, "adorderid") //23


        )
        //电话号码默认不显示
        defaultViewData[22].show = false
        defaultViewData[22].id = data.phone

//        defaultViewData[23].show = false

        //线索有效性，0：继续跟进；1：有效；2：无效
        when (data.effective) {
            "0" -> {
                ChangeData(youxiaoPos)
//                defaultViewData[0].value = "待判定"
//                defaultViewData[0].id = "0"
            }
            "1" -> {
                ChangeData(youxiaoPos)
                defaultViewData[0].value = "有效"
                defaultViewData[0].id = "1"
            }
            "2" -> {
                ChangeData(wuxiaoPos)
                defaultViewData[0].value = "无效"
                defaultViewData[0].id = "2"
                //联动数据
                LiandongData("无效")
            }
            else -> {
                ChangeData(morenpop)
            }
        }

        if (data.effective != "0") {
            defaultViewData[0].show = false
        }

        defaultViewData[20].value = data.seriesname
        defaultViewData[20].id = data.series

        defaultViewData[21].value = data.specname
        defaultViewData[21].id = data.spec

        defaultViewData[21].spec_select = data.spec_select



        //联系方式不是手机号，显示并可修改
        if (!FunctionUtils.isPhone3(data.phone)) {
            defaultViewData[22].show = true
        }

        initViewColor(defaultViewData)

        viewList.value = defaultViewData.toList()
        //初始化数据
        if (leve != null && leve != "") {
            if (leve == "O" || leve == "D") {
                defaultViewData[0].value = "有效"
                defaultViewData[0].id = "1"
            }
            position = 11
            //设置回调参数
            viewList.value?.get(position)?.apply {
                for (i in this.poplistdata) {
                    if (i.ikey == leve) {
                        this.value = i.name
                        this.id = i.id
                        this.ikey = i.ikey
                        for (j in this.poplistdata) {
                            j.IsSelect = j.id == i.id
                        }
                    }
                }
            }
            setViewData2()
        }
        if(come.equals("keliu")){
            //客流接待进入,跟进方式自动选择为到店
            defaultViewData[2].value = "到店"
            defaultViewData[2].ikey = "arrive"
            for (gen in genjinpoplist) {
                if(gen.ikey.equals("arrive")){
                    defaultViewData[2].id = gen.id
                }
            }
            position = 2
            setViewData2()
            if(keliudata!=null){
                setDaoDaian(keliudata!!)
            }
        }
        //对客流接待进入，判断是否试驾
        if(keliudata!=null){
            if(keliudata?.is_driving == 1){
                defaultViewData[9].value="是"
                defaultViewData[9].id="1"
            }
        }

        if(isNew){
            //不显示意向车系，车型
            defaultViewData[20].show = false
            defaultViewData[21].show = false
        }
    }


    /**
     * 点击日期回调
     */
    fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
        this.year = year.toString()
        this.month = month.toString()
        this.day = day.toString()
        val timePickerFragment = TimePickerFragment()
        timePickerFragment.clickOk = this::onTimeSet
        timePickerFragment.show(activity?.supportFragmentManager!!, "timePicker")
    }

    /**
     * 点击时间回调
     */
    fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
        defaultViewData[position].value = FunctionUtils.formatTime(year, month, day, hourOfDay, minute)
        defaultViewData[position].id = FunctionUtils.formatTime(year, month, day, hourOfDay, minute)
        if(position == 3){
            //到店时间
            if (defaultViewData[2].ikey == "arrive") {
                //无展督模式
                if(MySharedPreferences.getLoginData()?.channel?.settings?.receive == 1){
                    defaultViewData[1].value = defaultViewData[position].value;
                    defaultViewData[1].id = defaultViewData[position].id;
                }
            }
        }
    }

    fun clickItem(view: View, item: KeyValueParam, position: Int) {
        this.position = position
        var content = view.context
        if(data.isapp == 1){
            if (position == 0 && defaultViewData[position].key.contains("有效性")) {
                MyToast("App订单不允许修改")
                return
            }
        }

        if (content is AppCompatActivity) {
            //从客流接待进入，跟进方式为到店，有效性为有效，且不可编辑
            if(come.equals("keliu")){
                if (position == 0 && defaultViewData[position].idname.equals("effective")) {
                    return
                }
                if (position == 2 && defaultViewData[position].idname.equals("connectway")) {
                    return
                }
            }
            //战败审核，跟进级别为F, 战败原因和战败原因分析默认显示，不可编辑
            if(position == 16){
                if(this.data.state.equals("23") && defaultViewData[11].id.equals("F")){
                    return
                }
            }
            //2020-04-22 跟进级别为”D“，按钮调整成“回访”和“退车“，回访有且只有“d”级，退车有且只有“O”级，且不可编辑
            if(position == 11){
                if(levelLock){
                    return
                }
            }

            //2021-2-25 对是否有预约进行判断  有： 跟进、取消试驾、分配
            if(!this.data.reserveid.equals("0") && this.data.reserveid.isNotEmpty() && canceldrive == 0 ){
                //不修改跟进时间，都不能选择
                if(isdrivetime == 0) {
                    if (position == 11 || position == 13 || position == 14 || position == 15) {
                        return
                    }
                }else if(isdrivetime == 1){
                    //修改跟进时间，下次跟进方式，到店事项不能选择
                    if (position == 14 || position == 15) {
                        return
                    }
                }
            }
            //2021-06-10  增加是否开启关联试驾按钮
            //开启”状态下，经销商在写跟进的时候，“是否试驾”选项不可以手动选择，客户通过系统进行了试驾，默认为“是”，且不能修改，同理未通过系统进行试乘试驾的，默认为“否”，同样不得修改；
            //当开关为“关闭”状态时，“是否试驾”的选项可以由销售顾问手动修改。
            if(position == 9) {
                if (this.data.sysdrive == 1) {
                    return
                }
                if(MySharedPreferences.getBaseData()?.sysconf?.sysdrive == 1){
                    return
                }
            }
            activity = content
            if (defaultViewData[position].key == "到店客户:") {
                if(!come.equals("keliu")){
                    //从客流接待进入，到店客户为默认当前客户， 不可更改
                    var intent = Intent(content, ChoiceCustomerActivity::class.java)
                    if(data.phone.isNotEmpty()) {
                        intent.putExtra("phone", data.phone)
                    }
                    if(data.tid!=null) {
                        if(data.tid.toInt()>0) {
                            intent.putExtra("tid", data.tid)
                        }
                    }
                    content.startActivityForResult(intent, 101)
                }
                return
            }
//            if (defaultViewData[position].key.contains("预订单")) {
//                var intent = Intent(content, ChoiceOrderActivity::class.java)
//                intent.putExtra("phone",this.data.phone)
//                content.startActivityForResult(intent, 102)
//                return
//            }
            if (defaultViewData[position].key.contains("时间")) {
                if(position == 1){
//                    if (defaultViewData[2].ikey == "arrive") {
//                        //时间不可选择
//                        return;
//                    }
                    return
                }
                val datePickerFragment = DatePickerFragment()
                datePickerFragment.clickOk = this::onDateSet
                if (defaultViewData[position].key == "跟进时间:") {
                    val c = Calendar.getInstance()
                    datePickerFragment.maxDate = c.timeInMillis
                    c.add(Calendar.DAY_OF_MONTH, -6)
                    datePickerFragment.minDate = c.timeInMillis
                } else {
                    //下次跟进时间
                    val c = Calendar.getInstance()
                    datePickerFragment.minDate = c.timeInMillis
                    if (alarmday != 0) {
                        c.add(Calendar.DAY_OF_MONTH, alarmday)
                        datePickerFragment.maxDate = c.timeInMillis
                    }
                    if(MySharedPreferences.getLoginData()?.channel?.settings?.receive == 1){
                        if (defaultViewData[position].key == "到店时间:") {
                            val c = Calendar.getInstance()
                            datePickerFragment.maxDate = c.timeInMillis
                            c.add(Calendar.DAY_OF_MONTH, -7)
                            datePickerFragment.minDate = c.timeInMillis
                        }
                        if (defaultViewData[position].key == "离店时间:") {
                            val c = Calendar.getInstance()
                            datePickerFragment.maxDate = c.timeInMillis
                            c.add(Calendar.DAY_OF_MONTH, -7)
                            datePickerFragment.minDate = c.timeInMillis
                        }
                    }
                }
                datePickerFragment.show(content.supportFragmentManager, "datePicker")
                return
            }
            if (defaultViewData[position].key.contains("意向车系") || defaultViewData[position].key.contains("意向车型")) {

                if(data.isapp == 1 && data.iseriesname.isNotEmpty() && data.ispecname.isNotEmpty() && data.iproductname.isNotEmpty()) {
                    MyToast("App订单不允许修改")
                    return
                }
                if(defaultViewData[position].key.contains("意向车系")  && !data.xiaodingChangeSeries()){
                    MyToast("小定订单不允许修改")
                    return
                }
                if(defaultViewData[position].key.contains("意向车型")  && !data.xiaodingChangeSpec()){
                    MyToast("小定订单不允许修改")
                    return
                }

                var intent = Intent(content, MarsChooseCarActivity::class.java)
                var car = CarBrandParam(data.brand, data.series, data.spec,"")
                car.brandname = data.brandname
                car.seriesname = data.seriesname
                car.specname = data.specname
                car.spec_select = data.spec_select
                intent.putExtra("car", car as Serializable)
                intent.putExtra("pos", 1)
                intent.putExtra("Isspec",true)

                if((data.appminiorder > 0 && data.series != "0") || (data.isapp > 0 && data.series != "0")){
                    intent.putExtra("frozenSeries",true)
                }

                content.startActivityForResult(intent, 104)
                return
            }
            //深拷贝
            var list = ArrayList<DialogParam>()
            var poplist = viewList.value!![position].poplistdata
            for (it in poplist) {
                //继续跟进 在线索未判断有效性时不能订车提车
                if (data.effective != "1" && position == 11 && defaultViewData[0].id == "0") {
                    if (it.ikey == "O" || it.ikey == "D") {
                    } else {
                        var item = DialogParam(it.name, it.id)
                        item.ikey = it.ikey
                        list.add(item)
                    }

                } else {
                    var item = DialogParam(it.name, it.id)
//                item.IsSelect = it.IsSelect
                    item.ikey = it.ikey
                    list.add(item)
                }
            }
            val newFragment = MyDialog.newInstance("请选择"
                    + viewList.value!![position].key.replace(":", ""), list,item.isMultiple)
            if(item.isMultiple){
                newFragment.huidiaMultiple = this::myPopMultiple
            }else {
                newFragment.huidia = this::myPop
            }
            newFragment.show(content.supportFragmentManager, "missiles")
        }
    }

    /**
     * 点击确定回调
     */
    fun myPop(item: DialogParam?) {
//        if (defaultViewData[0].value == "" && position != 0) {
//            MyToast( "请选择有效性")
//            return
//        }
        //设置回调参数
        item?.apply {
            viewList.value?.get(position)?.apply {
                this.value = item.name
                this.id = item.id
                this.ikey = item.ikey
                for (i in this.poplistdata) {
                    i.IsSelect = i.id == item.id
                }
            }
        }
        setViewData2()
    }
    fun myPopMultiple(items: List<DialogParam>?) {
//        if (defaultViewData[0].value == "" && position != 0) {
//            MyToast( "请选择有效性")
//            return
//        }
        //设置回调参数
        items?.apply {
            viewList.value?.get(position)?.apply {
                var names:String = ""
                var id :String = ""
                var key :String = ""
                for(item in items){
                    if(names.length>0) names += ','
                    names += item.name

                    if(id.length>0) id += ','
                    id += item.id

                    if(key.length>0) key += ','
                    key += item.ikey

                    for (i in this.poplistdata) {
                        i.IsSelect = i.id == item.id
                    }
                }
                this.value = names
                this.id = id
                this.ikey = key
            }
        }
        setViewData2()
    }

    /**
     * 车型
     */
    fun setFollowCardata(data: CarBrandParam) {
        defaultViewData[20].value = data.seriesname
        defaultViewData[20].id = data.series

        defaultViewData[21].value = data.specname
        defaultViewData[21].id = data.spec
        defaultViewData[21].spec_select = data.spec_select
        setViewData2()
    }
    /**
     * 动态改变数据2
     */
    private fun setViewData2() {
        bottom.set("完成")
        state = ""
        //到店自动变有效
        if (position == 2 && defaultViewData[2].ikey == "arrive") {
            defaultViewData[0].value = "有效"
            defaultViewData[0].id = "1"
        }

        if (defaultViewData[0].value == "有效" || defaultViewData[0].value == "待判定") {
            defaultViewData[20].isMust = true
            defaultViewData[21].isMust = defaultViewData[21].spec_select == 1

            if (defaultViewData[2].ikey == "arrive") {
                //有效到店战败
                if (defaultViewData[11].ikey == "F") {
                    ChangeData(zhanbaiPop)
                    state = "F"
                }

                //有效到店订车
                if (defaultViewData[11].ikey == "O") {
                    if(data.vin.isNullOrEmpty()){
                        ChangeData(dingche)
                        state = "O"
                        bottom.set("下一页")
                    }
                }
                //有效到店提车
                if (defaultViewData[11].ikey == "D") {
                    if(data.vin.isNullOrEmpty()){
                        ChangeData(dingche)
                        state = "D"
                        bottom.set("下一页")
                    }
                }
                //有效到店其他
                if (defaultViewData[11].ikey != "O" && defaultViewData[11].ikey != "F") {
                    ChangeData(namelist)
                }
            } else {
                when (defaultViewData[11].ikey) {
                    "F" -> {
                        //有效其他战败
                        ChangeData(zhanbaiqitaPop)
                        state = "F"
                    }
                    "O" -> {
                        //有效其他订车
//                        if(data.vin.isNullOrEmpty()) {
//                            ChangeData(dingche2)
//                            state = "O"
//                            bottom.set("下一页")
//                        }else{
//                            ChangeData(youxiaoPos)
//                        }
                        if(data.Level.equals("O")){
                            ChangeData(youxiaoPos)
                        }else{
                            ChangeData(dingche2)
                            state = "O"
                            bottom.set("下一页")
                        }
                    }
                    "D" -> {
                        //有效其他提车
                        if(data.vin.isNullOrEmpty()) {
                            ChangeData(dingche2)
                            state = "D"
                            bottom.set("下一页")
                        }else{
                            ChangeData(youxiaoPos)
                        }
                    }
                    else -> {
                        //有效其他
                        ChangeData(youxiaoPos)
                    }
                }
            }

        } else {
            if (defaultViewData[0].value == "") {
                //默认
//                if(isNew){
//                    ChangeData(youxiaoPos)
//                }else {
//                    ChangeData(morenpop)
//                }
                ChangeData(youxiaoPos)
                defaultViewData[20].isMust = true
                defaultViewData[21].isMust = defaultViewData[21].spec_select == 1
            } else {
                //无效
                ChangeData(wuxiaoPos)
                if (position == 0) {
                    defaultViewData[2].value = ""
                    defaultViewData[2].id = ""
                    defaultViewData[2].ikey = ""
                }
                defaultViewData[20].isMust = false
                defaultViewData[21].isMust = defaultViewData[21].spec_select == 1
            }
        }
        //下次跟进方式为到店
        if (defaultViewData[14].ikey == "arrive") {
            defaultViewData[15].show = true
            defaultViewData[15].isMust = true
            //  O 级线索(state = 5的线索)跟进时, 下次跟进方式选择到店,到店事项 需要去掉订车 (基础数据到店事项的ikey = 'done') ;
            // D 级线索(state = 10的线索)跟进时
            // 下次跟进方式选择到店,到店事项 需要去掉订车 (基础数据到店事项的ikey = 'done') 和提车 (基础数据到店事项的ikey = 'deliver')
            if(defaultViewData[11].ikey.equals("O")){
                var storeitemslist = ArrayList<DialogParam>()
                baseData?.storeitems?.apply {
                    for (i in this) {
                        if(i.ikey.equals("done"))continue
                        var item = DialogParam(i.title, i.id.toString())
                        item.ikey = i.ikey
                        storeitemslist.add(item)
                    }
                }
                defaultViewData[15].poplistdata = storeitemslist
            }else if(defaultViewData[11].ikey.equals("D")){
                var storeitemslist = ArrayList<DialogParam>()
                baseData?.storeitems?.apply {
                    for (i in this) {
                        if(i.ikey.equals("done") || i.ikey.equals("deliver"))continue
                        var item = DialogParam(i.title, i.id.toString())
                        item.ikey = i.ikey
                        storeitemslist.add(item)
                    }
                }
                defaultViewData[15].poplistdata = storeitemslist
            }
        }

        if (data.effective == "1" || data.effective == "2") {
            defaultViewData[0].show = false
        }


        initViewColor(defaultViewData)
    }

    /**
     * 初始化颜色
     */
    private fun initViewColor(list: Array<KeyValueParam>) {
        var position = 0
        for (i in list) {
            if (i.show) {
                i.position = position
                position++
            }
        }
        for (i in list) {
            i.isfood = i.position == position - 1
        }
    }

    /**
     * 数据联动
     */
    private fun LiandongData(s: String) {
        when (s) {
            "无效" -> {
                for (i in defaultViewData) {
                    if (i.key == "本次跟进方式:") {
                        i.value = ""
                    }
                }
            }
            "到店" -> {
                for (i in defaultViewData) {
                    if (i.key == "有效性:") {
                        i.value = "有效"
                        i.id = "1"
                    }
                }
            }
        }
    }

    /**
     * 改变数据
     */
    private fun ChangeData(data: Array<String>) {
        for (i in defaultViewData) {
            i.show = false
            for (j in data) {
                if (j == i.key) {
                    i.show = true
                }
                //跟进情况
                if (i.idname == "followinfo" && j == "跟进情况:") {
                    i.show = true
                }
            }
        }
        //当前等级D提车 选择O订车
        if (defaultViewData[11].show && this.data.Level == "D" && defaultViewData[11].ikey == "O") {
            defaultViewData[7].key = "退库原因:"
        } else {
            defaultViewData[7].key = "跟进情况:"
        }
        if (defaultViewData[2].ikey == "arrive") {
            //无展督模式 跟进方式为到店 需要选择到店时间、离店时间、到店人数，不需要选择到店客户
            defaultViewData[1].isEdit = false
            defaultViewData[1].isEnable = false
            if(MySharedPreferences.getLoginData()?.channel?.settings?.receive == 1){
                defaultViewData[3].show = true
                defaultViewData[3].isMust = true
                defaultViewData[4].show = true
                defaultViewData[4].isMust = true
                defaultViewData[5].show = true
                defaultViewData[5].isMust = true
                defaultViewData[8].show = false
            }
        }
//        else{
//            defaultViewData[1].isEnable = true
//        }

        //清空隐藏view数据
        for (i in defaultViewData) {
            if (!i.show && i.key != "下次到店事项:") {
                i.value = ""
                i.id = ""
                i.ikey = ""
            }
        }
        //是否试驾为空并且显示  那么设置默认值 不试驾
        if (defaultViewData[9].show &&defaultViewData[9].value.isNullOrBlank() ){
            defaultViewData[9].value="否"
            defaultViewData[9].id="0"
        }

        //设置下次跟新时间
        var i = defaultViewData[11]//跟进级别

        if (i.show && position == 11) {
            var initNextTime = true
            //跟进以及基础数据中的追踪报警时间：天数为0则下次跟进时间、下次跟进方式非必填，非0则必填。若选择其中一项，则另一项也必填，D-》D为特殊情况，不受报警时间影响，为非必填。非必填选项均不填入默认值。
            //O\D追踪报警时间非0,时   N,H,A,B,C 到O   \    O到D应当为必填且有默认值。
            var isMust = true;
            if(i.ikey.equals("D")|| i.ikey.equals("O")){
                for(l in this.data.levelList){
                    if(l.ikey.equals(i.value)){
                        if(l.settings.alarmday == 0){
                            isMust = false
                        }
                    }
                }
                if(isMust){
                    if(i.value.equals("D") && this.data.Level.equals("D")){
                        isMust = false
                    }
                }
            }
            if(isMust){
                defaultViewData[13].isMust = true
                defaultViewData[14].isMust = true
            }else{
                defaultViewData[13].isMust = false
                defaultViewData[14].isMust = false
                defaultViewData[13].id = ""
                initNextTime = false
            }

            if(i.ikey.equals("F")){
                defaultViewData[13].show = false
                defaultViewData[14].show = false

                defaultViewData[16].isMust = true
                defaultViewData[17].isMust = true
            }

            //战败审核，跟进级别为F, 战败原因和战败原因分析默认显示，不可编辑
            if(this.data.state.equals("23")){
                if(i.ikey.equals("F")){
                    defaultViewData[16].value = this.data.giveupcausename
                    defaultViewData[16].id = this.data.giveupcause
                    defaultViewData[17].id= this.data.failurereason
                    defaultViewData[17].isEdit= false
                }
            }
            if(initNextTime) {
                for (item in this.data.levelList) {
                    //下次跟进时间
                    var temtime = defaultViewData[13]
                    //下次跟进时间显示并且跟进级别有数据 那么久根据跟进级别设置下次跟进时间
                    if (temtime.show && item.ikey == i.ikey) {
                        val c = Calendar.getInstance()
                        val hour = c.get(Calendar.HOUR_OF_DAY)
                        val minute = c.get(Calendar.MINUTE)
                        var s = item.settings.alarmtime.split(" ")
                        alarmday = item.settings.alarmday
                        if (s.size >= 2) {
                            temtime.value = s[0] + " " + hour + ":" + minute
                            temtime.id = s[0] + " " + hour + ":" + minute
                        } else {
                            temtime.value = ""
                            temtime.id = ""
                        }
                    }
                }
            }else{
                defaultViewData[13].value = ""
                defaultViewData[13].id = ""
            }
        }
        if (this.data.effective != "1" && position == 0 && defaultViewData[0].id == "0") {
            defaultViewData[11].ikey = ""
            defaultViewData[11].value = ""
            defaultViewData[11].id = ""
        }
        if(isNew){
            //不显示意向车系，车型
            defaultViewData[20].show = false
            defaultViewData[21].show = false
        }

        if(!this.data.reserveid.equals("0") && this.data.reserveid.isNotEmpty() && canceldrive == 0 && isdrivetime == 0){
            //2021-2-25 对是否有预约进行判断  有： 跟进、取消试驾、分配
            //1,该reserveid > 0 且点击确认修改预约试驾时间按钮, 下次跟进时间销售顾问可以选择H级限制的时间; 2,该reserveid > 0 没有点击修改预约试驾时间按钮 下次跟进时间需要回填该时间
            defaultViewData[13].value = this.data.reservetime
            defaultViewData[13].id = this.data.reservetime
            //H级别的唯一标识ikey 1,该reserveid > 0 且没有点击取消时间按钮 需要回填H级
            defaultViewData[11].poplistdata.forEach {
                if (it.id == this.data.reservecustomerlevelikey) {
                    defaultViewData[11].value = it.name
                    defaultViewData[11].ikey = this.data.reservecustomerlevelikey
                    defaultViewData[11].id = this.data.reservecustomerlevelikey
                }
            }
            //跟进方式为到店的唯一标识ikey 1,该reserveid > 0 且没有点击取消时间按钮 需要下次跟进方式为到店
            defaultViewData[14].poplistdata.forEach {
                if (it.id == this.data.reservencwayid) {
                    defaultViewData[14].value = it.name
                    defaultViewData[14].ikey= this.data.reservencwayikey
                    defaultViewData[14].id = this.data.reservencwayid
                }
            }
            //到店事项为'洽谈'的唯一标识 1,该reserveid > 0 且没有点击取消时间按钮 需要到店事项方式为'洽谈'
            defaultViewData[15].poplistdata.forEach {
                if (it.id == this.data.reservestoreitemsid) {
                    defaultViewData[15].value = it.name
                    defaultViewData[15].ikey= this.data.reservestoreitemsikey
                    defaultViewData[15].id = this.data.reservestoreitemsid
                }
            }
            defaultViewData[11].isEnable = false
            defaultViewData[13].isEnable = false
            defaultViewData[14].isEnable = false
            defaultViewData[15].isEnable = false
        }

        if (FunctionUtils.isPhone3(this.data.phone)) {
            defaultViewData[22].show = false
        }

//        if(defaultViewData[11].ikey == "O" ){ //&& this.data.adorder == 1
////            在线下定需求中, 跟进选择O级之后,如果adorder == 1 需要绑定预订单, 选择对应预订单后 需要传 预订单数据的, adorderid
//            defaultViewData[23].show= true
//            defaultViewData[23].isMust = false
//        }
    }

    /**
     * 到店数据回调
     */
    fun setDaoDaian(data: Data) {
        if (!data.phone.equals("") && !this.data.phone.equals(data.phone)) {
            MyToast("所选到店客户与该线索信息的电话号码不一致")
        }
        for (item in defaultViewData) {
            if (item.key == "到店客户:") {
                item.value = data.uname
                item.id = data.id.toString()
            }

        }
        if(data.is_driving == 1) {
            defaultViewData[9].value="是"
            defaultViewData[9].id="1"
        }

        if (defaultViewData[2].ikey == "arrive") {
            //展督模式 2021-2-22 CEM取消到店客户 跟进时间回填
//            if(MySharedPreferences.getLoginData()?.channel?.settings?.receive == 0){
//                defaultViewData[1].value = data.arrivetime
//                defaultViewData[1].id = data.arrivetime
//            }
        }

    }

    fun setOrder(order:OrderChooseData){
        defaultViewData[23].value= order.uname
        defaultViewData[23].id= order.id.toString()

        yudingdanData = order

        //绑定预计
        var carBrandParam = CarBrandParam()
        carBrandParam.series = order.series
        carBrandParam.seriesname = order.seriesname
        carBrandParam.spec = order.spec
        carBrandParam.specname = order.specname
        carBrandParam.aicname = order.productname
        carBrandParam.aic = order.product


        carBrandParam.excolor_code = order.exterior_code
        carBrandParam.intercolor_s_code = order.interior_code


        setCardata(carBrandParam)
    }

    /*************************订车******************/


    var bookingViewData = MutableLiveData<List<KeyValueParam>>()
    //订车
    private var booking: Array<KeyValueParam>


    init {
        /***订车***/
        //证件类型
        var cardtypelist = ArrayList<DialogParam>()

        baseData?.cardType?.apply {
            this.forEach {
                var item0 = DialogParam(it.title, it.id.toString())
                cardtypelist.add(item0)
            }
        }

        //客户类型
        var temlist8 = ArrayList<DialogParam>()
//        baseData?.customertype?.apply {
//            var index = 0
//            temlist8.add(DialogParam(this.key1, "1"))
//            temlist8.add(DialogParam(this.key2, "2"))
//        }


        //购买类型
        var temlist9 = ArrayList<DialogParam>()
        baseData?.purchasetype?.apply {
//            temlist9.add(DialogParam(this.key1, "1"))
//            temlist9.add(DialogParam(this.key2, "2"))
//            temlist9.add(DialogParam(this.key3, "3"))
        }

        //key: String, type: Int = 1, idname: String, sontype: Int = 1, value: String = "", id: String = "", isEdit: Boolean = true
        booking = arrayOf(
                KeyValueParam("预订车系:", 1, "iseries", isMust = true),
                KeyValueParam("预定车型:", 1, "ispec", isMust = true),
                KeyValueParam("预定产品:", 1, "iproduct", isMust = true),
                KeyValueParam("预订车辆颜色:", 1, "strikeexterior",2, isMust = true),
                KeyValueParam("预订内饰颜色:", 1, "strikeinterior",2, isMust = true),
                KeyValueParam("签约时间:", 2, "endtime",sontype = 2, isMust = true,isEdit = false),
                KeyValueParam("证件类型:", cardtypelist, "cardtype", isMust = true),
                KeyValueParam("证件号码:", 2, "cardno", 2,isMust = true),
                KeyValueParam("生日:", 1, "birthday", isMust = true),

                KeyValueParam("订单号:", 2, "ordernum", 2),
                KeyValueParam("预订价格:", 2, "strikeprice", isMust = true),
                KeyValueParam("客户类型:", temlist8, "customertype", isMust = true),
                KeyValueParam("购买类型:", temlist9, "purchasetype", isMust = true),
                KeyValueParam("地区:", 1, "provincegroup",isMust = true),
                KeyValueParam("详细地址:", 2, "address", 2, isMust = true),
                KeyValueParam("邮政编码:", 2, "postcode", 2)
        )
        //订车车型默认数据

//        //签约时间
        var time = if (data.endtime.isNullOrBlank() || data.endtime <= "0") {
            FunctionUtils.getTime()
        } else {
            data.endtime
        }
        booking[5].id = time
        booking[5].value = time

        booking[3].isEdit= false
        booking[4].isEdit= false

        if(data.isapp == 1 && data.cardtype.isNotEmpty()){
            booking[6].isEnable = false
        }

        if(data.isapp == 1 && data.cardno.isNotEmpty()){
            booking[7].isEnable = false
        }

        if(data.isapp == 1 && data.birthday.isNotEmpty()){
            booking[8].isEnable = false
        }

        if(data.isapp == 1 && data.strikeprice.isNotEmpty()){
            booking[10].isEnable = false
        }
        if(data.isapp == 1 && data.customertype.isNotEmpty()){
            booking[11].isEnable = false
        }
        if(data.isapp == 1){
            booking[9].isEnable = false



            //预订车系  预定车型  预定产品  预订车辆颜色  预订内饰颜色
            booking[0].value = data.iseriesname
            booking[0].id = data.iseries

            booking[1].value = data.ispecname
            booking[1].id = data.ispec

            booking[2].value = data.aicname
            booking[2].id = data.aic

            booking[3].value = data.strikeexteriorname
            booking[3].id = data.strikeexterior

            booking[4].value = data.strikeinteriorname
            booking[4].id = data.strikeinterior

            if(data.ordernum.isNotEmpty()){
                booking[9].id = data.ordernum
                booking[9].value = data.ordernum
            }
            if(data.strikeprice.isNotEmpty()){
                booking[10].id = data.strikeprice
                booking[10].value = data.strikeprice
            }
        }

        if(data.customertype.isNotEmpty()){
            baseData?.customertype?.apply {
//                if("1" == data.customertype){
//                    booking[11].value = this.key1
//                    booking[11].id = "1"
//                }
//                if("2" == data.customertype){
//                    booking[11].value = this.key2
//                    booking[11].id = "2"
//                }
            }
        }
        if(data.purchasetype.isNotEmpty()){
            baseData?.purchasetype?.apply {
//                if("1" == data.purchasetype){
//                    booking[12].value = this.key1
//                    booking[12].id = "1"
//                }
//                if("2" == data.purchasetype){
//                    booking[12].value = this.key2
//                    booking[12].id = "2"
//                }
//                if("3" == data.purchasetype){
//                    booking[12].value = this.key3
//                    booking[12].id = "3"
//                }
            }
        }
        //证件类型，证件号码回填
        if(data.cardtype.isNotEmpty()){
            baseData?.cardType?.apply {
                this.forEach {
                    if(it.id.equals(data.cardtype)){
                        booking[6].value = it.title
                        booking[6].id = it.id.toString()
                    }
                }
            }
        }
        if(data.cardno.isNotEmpty()){
            booking[7].id = data.cardno
            booking[7].value = data.cardno
        }

        this.bookingViewData.postValue(booking.toList())

        initViewColor(booking)
    }

    //点击位置
    var positionBooking = 0
    var activityBooking: AppCompatActivity? = null

    fun clickBookingItem(view: View, item: KeyValueParam, position: Int) {
        this.positionBooking = position
        var content = view.context

        if(data.isapp == 1) {

            if ((booking[positionBooking].key.contains("证件类型") && data.cardtype.isNotEmpty() && !data.cardtype.equals("0")) ||
                    (booking[positionBooking].key.contains("客户类型") && data.customertype.isNotEmpty() && !data.customertype.equals("0")) ||
                    (booking[positionBooking].key.contains("预订车系") && data.iseries != "0") ||
                    (booking[positionBooking].key.contains("预定车型") && data.ispec != "0") ||
                    (booking[positionBooking].key.contains("预定产品") && data.productname.isNotEmpty()) ||
                    booking[positionBooking].key.contains("预订车辆颜色") ||
                    booking[positionBooking].key.contains("预订内饰颜色")) {
                MyToast("App订单不允许修改")
                return
            }
        }

        if (content is AppCompatActivity) {
            activityBooking = content
            if (booking[positionBooking].key == "预订车系:" || booking[positionBooking].key == "预定车型:" || booking[positionBooking].key == "预定产品:") {
                //判断当前是否有预计单 ， 预计单的是否客户已同意换车
                var carBrandParam = CarBrandParam()
                carBrandParam.spec_select = data.spec_select
                var enableChange = true
                if(yudingdanData!=null && yudingdanData?.ischange != 2){
                    enableChange = false

                    if(yudingdanData?.ordertype  == 1){
                        enableChange = true
                        carBrandParam.series = yudingdanData?.series!!
                        carBrandParam.seriesname = yudingdanData?.seriesname!!
                    }
                }

                if(data.appminiorder > 0){
                    carBrandParam.series = yudingdanData?.series!!
                    carBrandParam.seriesname = yudingdanData?.seriesname!!
                }

                if(data.isapp > 0){
                    carBrandParam.series = data.iseries
                    carBrandParam.seriesname = data.iseriesname
                }

                if(enableChange  || (data.isapp > 0 && data.iseries != "0")) {
                    var intent = Intent(content, MarsChooseCarActivity::class.java)
                    intent.putExtra("car", carBrandParam)
                    intent.putExtra("frozenSeries", true)
                    content.startActivityForResult(intent, 101)
                }
                return
            }
            if (booking[positionBooking].key.contains("预订车辆颜色") || booking[positionBooking].key.contains("预订内饰颜色")) {
                return
            }
            if (booking[positionBooking].key.contains("地区:")) {
                var content = view.context
                if (content is AppCompatActivity) {
                    var intent = Intent(content, ChooseCityActivity::class.java)
                    content.startActivityForResult(intent, 104)
                }
                return
            }
            if (booking[positionBooking].key.contains("生日")) {
                var c = Calendar.getInstance()
                val datePickerFragment = DatePickerFragment()
                datePickerFragment.clickOk = this::onDateSetBookingBirthday
                datePickerFragment.maxDate = c.timeInMillis
                datePickerFragment.isTHEME_HOLO_LIGHT = true
                datePickerFragment.show(content.supportFragmentManager, "datePicker")
                return
            }
//            if (booking[positionBooking].key.contains("签约时间")) {
//                var c = Calendar.getInstance()
//                val datePickerFragment = DatePickerFragment()
//                datePickerFragment.clickOk = this::onDateSetBooking
//                datePickerFragment.maxDate = c.timeInMillis
//                datePickerFragment.show(content.supportFragmentManager, "datePicker")
//                return
//            }
            //深拷贝
            var list = ArrayList<DialogParam>()
            var poplist = booking[positionBooking].poplistdata
            for (it in poplist) {
                var item = DialogParam(it.name, it.id)
                item.IsSelect = it.IsSelect
                item.ikey = it.ikey
                list.add(item)
            }
            val newFragment = MyDialog.newInstance("请选择"
                    + booking[positionBooking].key.replace(":", ""), list)
            newFragment.huidia = this::myPopBooking
            newFragment.show(content.supportFragmentManager, "missiles")
        }
    }

    /**
     * 点击确定回调
     */
    fun myPopBooking(item: DialogParam?) {
        //设置回调参数
        item?.apply {
            bookingViewData.value?.get(positionBooking)?.apply {
                this.value = item.name
                this.id = item.id
                this.ikey = item.ikey
                for (i in this.poplistdata) {
                    i.IsSelect = i.id == item.id
                }
            }
        }

        initViewColor(booking)
    }

    fun onBookingTextChanged(position: Int) {
        if(position!=7)return
        if(booking[6].id.equals("1")) {
            this.positionBooking = position
            if (booking[positionBooking].key == "证件号码:") {
                //身份证验证
                if (CheckIdCard.check(booking[7].id)) {
                    booking[8].id = CheckIdCard.getBirthDayPart(booking[7].id)
                    booking[8].value = booking[8].id
                }
            }
        }
    }

    //年月日
    var yearBooking = ""
    var monthBooking = ""
    var dayBooking = ""
    /**
     * 点击日期回调
     */
    fun onDateSetBooking(view: DatePicker, year: Int, month: Int, day: Int) {
        this.yearBooking = year.toString()
        this.monthBooking = month.toString()
        this.dayBooking = day.toString()
        val timePickerFragment = TimePickerFragment()
        timePickerFragment.clickOk = this::onTimeSetBooking
        timePickerFragment.show(activityBooking?.supportFragmentManager!!, "timePicker")
    }

    fun onDateSetBookingBirthday(view: DatePicker, year: Int, month: Int, day: Int) {
        this.yearBooking = year.toString()
        this.monthBooking = month.toString()
        this.dayBooking = day.toString()
        booking[positionBooking].value = FunctionUtils.formatTime(yearBooking, monthBooking, dayBooking)
        booking[positionBooking].id = FunctionUtils.formatTime(yearBooking, monthBooking, dayBooking)
    }

    /**
     * 点击时间回调
     */
    fun onTimeSetBooking(view: TimePicker, hourOfDay: Int, minute: Int) {
        booking[positionBooking].value = FunctionUtils.formatTime(yearBooking, monthBooking, dayBooking, hourOfDay, minute)
        booking[positionBooking].id = FunctionUtils.formatTime(yearBooking, monthBooking, dayBooking, hourOfDay, minute)
    }

    /**
     * 车型
     */
    fun setCardata(data: CarBrandParam) {
        booking[0].value = data.seriesname
        booking[0].id = data.series

        booking[1].value = data.specname
        booking[1].id = data.spec
        booking[1].spec_select = data.spec_select

        booking[2].value = data.aicname
        booking[2].id = data.aic
        booking[2].spec_select = data.spec_select

        booking[3].spec_select = data.spec_select
        booking[4].spec_select = data.spec_select

        booking[1].isMust = data.spec_select == 1
        booking[2].isMust = data.spec_select == 1
        booking[3].isMust = data.spec_select == 1
        booking[4].isMust = data.spec_select == 1

        booking[3].value = ""
        booking[3].id = "0"
        booking[4].value = ""
        booking[4].id = "0"

        var baseDataParam: BaseDataParam? = MySharedPreferences.getBaseData()

        baseDataParam?.apply {
            if(data.excolor_code.isNotEmpty()){
                if(this.exterior!=null){
                    for (item in this.exterior) {
                        if(item.ikey.equals(data.excolor_code)){
                            booking[3].value = item.title
                            booking[3].id = data.excolor_code
                        }
                    }
                }
            }
            if(data.intercolor_s_code.isNotEmpty()){
                if(this.interior!=null){
                    for (item in this.interior) {
                        if(item.ikey.equals(data.intercolor_s_code)){
                            booking[4].value = item.title
                            booking[4].id = data.intercolor_s_code
                        }
                    }
                }
            }
        }

        setViewData2()
    }
    /**
     * 设置城市
     */
    fun setCityData(show: String, id: String) {
        booking[13].value = show
        booking[13].id = id
    }

    /*************************提车******************/

    //提车
    var LiftcarViewData = MutableLiveData<List<KeyValueParam>>()
    private var Liftcar: Array<KeyValueParam>

    init {

        booking[1].spec_select = data.spec_select


        booking[2].spec_select = data.spec_select

        booking[3].spec_select = data.spec_select
        booking[4].spec_select = data.spec_select

        booking[1].isMust = data.spec_select == 1
        booking[2].isMust = data.spec_select == 1
        booking[3].isMust = data.spec_select == 1
        booking[4].isMust = data.spec_select == 1
        /***订车***/
        //订车车辆颜色
        var exteriorlist = ArrayList<DialogParam>()
        baseData?.exterior?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                exteriorlist.add(item)
            }

        }
        //内饰颜色
        var interiorlist = ArrayList<DialogParam>()
        baseData?.interior?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                interiorlist.add(item)
            }
        }

        //购买类型
        var buytype = arrayOf(
                DialogParam("首购", "1"),
                DialogParam("增购", "2"),
                DialogParam("置换", "3")
        )

        //保险公司
        var insurerlist = ArrayList<DialogParam>()
//        baseData?.insurer?.apply {
//            for (i in this) {
//                var item = DialogParam(i.title, i.id.toString())
//                item.ikey = i.ikey
//                insurerlist.add(item)
//            }
//        }

        var purchasetype = when (data.purchasetype) {
            "1" -> "首购"
            "2" -> "增购"
            "3" -> "置换"
            else -> ""
        }

        var time = if (data.delivertime.isNullOrBlank() || data.delivertime <= "0") {
            FunctionUtils.getTime()
        } else {
            data.delivertime
        }

        //付款方式
        var paymentwaylist = ArrayList<DialogParam>()
        baseData?.paymentway?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                paymentwaylist.add(item)
            }
        }
        //会员
        var mlevellist = ArrayList<DialogParam>()
//        baseData?.mlevel?.apply {
//            for (i in this) {
//                var item = DialogParam(i.title, i.id.toString())
//                item.ikey = i.ikey
//                mlevellist.add(item)
//            }
//
//        }

        Liftcar = arrayOf(
                KeyValueParam("提车时间:", 1, "delivertime", value = time, id = time, isMust = true),
                KeyValueParam("提车品牌/车系:", 1, "dbrandgroup",
                        value = data.dbrandname + " " + data.dseriesname + " " + data.dspecname, id = data.dbrandgroup, isEdit =  statkun != 1, isMust = true),
                KeyValueParam("提车车辆颜色:", exteriorlist, "deliverexterior",
                        value = data.deliverexteriorname, id = data.deliverexterior, isEdit = statkun != 1, isMust = true),
                KeyValueParam("提车内饰颜色:", interiorlist, "deliverinterior",
                        value = data.deliverinteriorname, id = data.deliverinterior, isEdit = statkun != 1, isMust = true
                ),
                KeyValueParam("购买类型:", buytype.toList(), "purchasetype",
                        value = purchasetype, id = data.purchasetype, isMust = true
                ),
                KeyValueParam("车牌号:", 2, "plate", 2),
                KeyValueParam("车架号:", 2, "vin", 2,
                        value = data.vin, id = data.vin, isEdit = statkun != 1
                ),
                KeyValueParam("保险公司:", insurerlist, "insurer"),
                KeyValueParam("保单号:", 2, "policyno", 2)
        )

        initViewColor(Liftcar)
        this.LiftcarViewData.postValue(Liftcar.toList())
    }

    //点击位置
    var positionLiftcar = 0
    var activityLiftcar: AppCompatActivity? = null

    fun clickLiftcarItem(view: View, item: KeyValueParam, position: Int) {
        if (!item.isEdit) {
            MyToast("无法修改")
            return
        }
        this.positionLiftcar = position
        var content = view.context

        if (content is AppCompatActivity) {
            activityLiftcar = content

            if (Liftcar[position].key.contains("时间")) {
                var c = Calendar.getInstance()
                val datePickerFragment = DatePickerFragment()
                datePickerFragment.clickOk = this::onDateSetLiftcar
                datePickerFragment.maxDate = c.timeInMillis
                datePickerFragment.show(content.supportFragmentManager, "datePicker")
                return
            }
            if (Liftcar[position].key == "提车品牌/车系:") {
                var intent = Intent(content, ChooseCarActivity::class.java)
                intent.putExtra("car", CarBrandParam())
                content.startActivityForResult(intent, 102)
                return
            }

            //深拷贝
            var list = ArrayList<DialogParam>()
            var poplist = Liftcar[position].poplistdata
            for (it in poplist) {
                var item = DialogParam(it.name, it.id)
                item.IsSelect = it.IsSelect
                item.ikey = it.ikey
                list.add(item)
            }
            val newFragment = MyDialog.newInstance("请选择"
                    + Liftcar[position].key.replace(":", ""), list)
            newFragment.huidia = this::myPopLiftcar
            newFragment.show(content.supportFragmentManager, "missiles")
        }
    }

    /**
     * 点击确定回调
     */
    fun myPopLiftcar(item: DialogParam?) {
        //设置回调参数
        item?.apply {
            LiftcarViewData.value?.get(positionLiftcar)?.apply {
                this.value = item.name
                this.id = item.id
                this.ikey = item.ikey
                for (i in this.poplistdata) {
                    i.IsSelect = i.id == item.id
                }
            }
        }
    }

    //年月日
    var yearLiftcar = ""
    var monthLiftcar = ""
    var dayLiftcar = ""
    /**
     * 点击日期回调
     */
    fun onDateSetLiftcar(view: DatePicker, year: Int, month: Int, day: Int) {
        this.yearLiftcar = year.toString()
        this.monthLiftcar = month.toString()
        this.dayLiftcar = day.toString()
        val timePickerFragment = TimePickerFragment()
        timePickerFragment.clickOk = this::onTimeSetLiftcar
        timePickerFragment.show(activityLiftcar?.supportFragmentManager!!, "timePicker")
    }

    /**
     * 点击时间回调
     */
    fun onTimeSetLiftcar(view: TimePicker, hourOfDay: Int, minute: Int) {
        Liftcar[positionLiftcar].value = FunctionUtils.formatTime(yearLiftcar, monthLiftcar, dayLiftcar, hourOfDay, minute)
        Liftcar[positionLiftcar].id = FunctionUtils.formatTime(yearLiftcar, monthLiftcar, dayLiftcar, hourOfDay, minute)
    }

    /**
     * 车型
     */
    fun setCardataLiftcar(data: CarBrandParam) {
        Liftcar[positionLiftcar].value = data.brandname + "  " + data.seriesname + "  " + data.specname
        Liftcar[positionLiftcar].id = data.brand + "," + data.series + "," + data.spec
    }

    //提车订车一体
    var BookingLiftcarViewData = MutableLiveData<List<KeyValueParam>>()
    private var BookingLiftcar: Array<KeyValueParam>

    init {
        /***订车***/
        //订车车辆颜色
        var exteriorlist = ArrayList<DialogParam>()
        baseData?.exterior?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                exteriorlist.add(item)
            }
        }
        //内饰颜色
        var interiorlist = ArrayList<DialogParam>()
        baseData?.interior?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                interiorlist.add(item)
            }
        }

        //购买类型
        var buytype = arrayOf(
                DialogParam("首购", "1"),
                DialogParam("增购", "2"),
                DialogParam("置换", "3")
        )

        //保险公司
        var insurerlist = ArrayList<DialogParam>()
//        baseData?.insurer?.apply {
//            for (i in this) {
//                var item = DialogParam(i.title, i.id.toString())
//                item.ikey = i.ikey
//                insurerlist.add(item)
//            }
//
//        }

        var purchasetype = when (data.purchasetype) {
            "1" -> "首购"
            "2" -> "增购"
            "3" -> "置换"
            else -> ""
        }

        //付款方式
        var paymentwaylist = ArrayList<DialogParam>()
        baseData?.paymentway?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                paymentwaylist.add(item)
            }
        }
        //按揭银行
        var banklist = ArrayList<DialogParam>()
        baseData?.bank?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                banklist.add(item)
            }
        }
        //会员
        var mlevellist = ArrayList<DialogParam>()
//        baseData?.mlevel?.apply {
//            for (i in this) {
//                var item = DialogParam(i.title, i.id.toString())
//                item.ikey = i.ikey
//                mlevellist.add(item)
//            }
//        }
        var time = if (data.endtime.isNullOrBlank() || data.endtime <= "0") {
            FunctionUtils.getTime()
        } else {
            data.endtime
        }
        var delivertime = if (data.delivertime.isNullOrBlank() || data.delivertime <= "0") {
            FunctionUtils.getTime()
        } else {
            data.delivertime
        }
        BookingLiftcar = arrayOf(
                KeyValueParam("签约时间:", 1, "endtime", isMust = true),  //0
                KeyValueParam("提车时间:", 1, "delivertime", value = delivertime, id = delivertime, isMust = true), //1
                KeyValueParam("提车品牌/车系:", 1, "dbrandgroup",
                        value = data.dbrandname + " " + data.dseriesname + " " + data.dspecname, id = data.dbrandgroup,
                        isEdit =  statkun != 1, isMust = true), //2
                KeyValueParam("提车车辆颜色:", exteriorlist, "deliverexterior",
                        value = data.deliverexteriorname, id = data.deliverexterior, isEdit = statkun != 1, isMust = true), //3
                KeyValueParam("提车内饰颜色:", interiorlist, "deliverinterior",
                        value = data.deliverinteriorname, id = data.deliverinterior, isEdit = statkun != 1, isMust = true
                ), //4

                KeyValueParam("付款方式:", paymentwaylist, "paymentway", isMust = true), //5
                KeyValueParam("按揭银行:", banklist, "loanbank", isMust = true), //6
                KeyValueParam("按揭服务费:", 2, "loanfee", isMust = true), //7
                KeyValueParam("预订价格:", 2, "strikeprice", isMust = true),//8
                KeyValueParam("车架号:", 2, "vin", 2,
                        value = data.vin, id = data.vin, isEdit = statkun != 1
                ),//9
                KeyValueParam("订单号:", 2, "ordernum", 2),//10
                KeyValueParam("车牌号:", 2, "plate", 2), //11
                KeyValueParam("保险公司:", insurerlist, "insurer"), //12
                KeyValueParam("保单号:", 2, "policyno", 2), //13
                KeyValueParam("购买类型:", buytype.toList(), "purchasetype",
                        value = purchasetype, id = data.purchasetype, isMust = true
                ),//14
                KeyValueParam("用品销售额:", 2, "supsales"), //15
                KeyValueParam("会员:", mlevellist, "mlevel"), //16
                KeyValueParam("其他费用:", 3, "vas") //17
        )

        BookingLiftcar[0].id = time
        BookingLiftcar[0].value = time



        //订车车型默认数据
        if (!data.ibrandgroup.isNullOrBlank() && !data.ibrandgroup.equals("0,0,0")) {
            BookingLiftcar[2].value = data.ibrandname + "  " + data.iseriesname + "  " + data.ispecname
            BookingLiftcar[2].id = data.ibrandgroup
        }else{
            //没有订车车型默认数据，将拟购品牌车系车型、车辆颜色、内饰颜色带入
            BookingLiftcar[2].value = data.brandname + "  " + data.seriesname + "  " + data.specname
            BookingLiftcar[2].id = data.brandgroup
        }
        //订车车辆颜色
        if (!data.strikeexteriorname.isNullOrBlank()) {
            BookingLiftcar[3].id = data.strikeexterior
            BookingLiftcar[3].value = data.strikeexteriorname
        }else{
            //没有订车车型默认数据，将拟购品牌车系车型、车辆颜色、内饰颜色带入
            BookingLiftcar[3].id = data.exterior
            BookingLiftcar[3].value = data.exteriorname
        }
        //订车内饰颜色
        if (!data.strikeinteriorname.isNullOrBlank()) {
            BookingLiftcar[4].id = data.strikeinterior
            BookingLiftcar[4].value = data.strikeinteriorname
        }else{
            BookingLiftcar[4].id = data.interior
            BookingLiftcar[4].value = data.interiorname
        }
        BookingLiftcar[6].show = false
        BookingLiftcar[7].show = false
        if(!data.paymentway.isNullOrEmpty()){
            BookingLiftcar[5].id = data.paymentway
            BookingLiftcar[5].value = data.paymentwayname
            if(data.paymentway.equals("7820")){
                BookingLiftcar[6].show = true
                BookingLiftcar[7].show = true
            }
        }

        if(!data.loanbank.isNullOrEmpty()){
            BookingLiftcar[6].id = data.loanbank
            BookingLiftcar[6].value = data.loanbankname
        }
        if(!data.loanfee.isNullOrEmpty()){
            BookingLiftcar[7].id = data.loanfee
        }

        if(!data.ordernum.isNullOrEmpty()){
            BookingLiftcar[10].id = data.ordernum
        }
        if(!data.strikeprice.isNullOrEmpty()){
            BookingLiftcar[8].id = data.strikeprice
        }
        if(!data.supsales.isNullOrEmpty()){
            BookingLiftcar[15].id = data.supsales
        }
        if(!data.mlevel.isNullOrEmpty()){
            BookingLiftcar[16].id = data.mlevel
            BookingLiftcar[16].value = data.mlevelname
        }
        if(!data.vas.isNullOrEmpty()){
            BookingLiftcar[17].id = data.vas
        }

        initViewColor(BookingLiftcar)
        this.BookingLiftcarViewData.postValue(BookingLiftcar.toList())
    }

    //点击位置
    var positionBookingLiftcar = 0
    var activityBookingLiftcar: AppCompatActivity? = null

    fun clickBookingLiftcarItem(view: View, item: KeyValueParam, position: Int) {
        if (!item.isEdit) {
            MyToast("无法修改")
            return
        }
        this.positionBookingLiftcar = position
        var content = view.context

        if (content is AppCompatActivity) {
            activityBookingLiftcar = content

            if (BookingLiftcar[position].key.contains("签约时间")) {
                var c = Calendar.getInstance()
                val datePickerFragment = DatePickerFragment()
                datePickerFragment.clickOk = this::onDateSetBookingLiftcar
                datePickerFragment.maxDate = c.timeInMillis
                datePickerFragment.show(content.supportFragmentManager, "datePicker")
                return
            }
            if (BookingLiftcar[position].key.contains("提车时间")) {
                var c = Calendar.getInstance()
                val datePickerFragment = DatePickerFragment()
                datePickerFragment.clickOk = this::onDateSetBookingLiftcar
//                datePickerFragment.maxDate = c.timeInMillis
                datePickerFragment.show(content.supportFragmentManager, "datePicker")
                return
            }
            if (BookingLiftcar[position].key == "提车品牌/车系:") {
                var intent = Intent(content, ChooseCarActivity::class.java)
                intent.putExtra("car", CarBrandParam())
                content.startActivityForResult(intent, 103)
                return
            }

            //深拷贝
            var list = ArrayList<DialogParam>()
            var poplist = BookingLiftcar[position].poplistdata
            for (it in poplist) {
                var item = DialogParam(it.name, it.id)
                item.IsSelect = it.IsSelect
                item.ikey = it.ikey
                list.add(item)
            }
            val newFragment = MyDialog.newInstance("请选择"
                    + BookingLiftcar[position].key.replace(":", ""), list)
            newFragment.huidia = this::myPopBookingLiftcar
            newFragment.show(content.supportFragmentManager, "missiles")
        }
    }

    /**
     * 点击确定回调
     */
    fun myPopBookingLiftcar(item: DialogParam?) {
        //设置回调参数
        item?.apply {
            BookingLiftcarViewData.value?.get(positionBookingLiftcar)?.apply {
                this.value = item.name
                this.id = item.id
                this.ikey = item.ikey
                for (i in this.poplistdata) {
                    i.IsSelect = i.id == item.id
                }
            }
        }
        //按揭显示
        if (BookingLiftcar[5].ikey == "loan") {
            BookingLiftcar[6].show = true
            BookingLiftcar[7].show = true
        } else {
            BookingLiftcar[6].show = false
            BookingLiftcar[7].show = false
        }
    }

    //年月日
    var yearBookingLiftcar = ""
    var monthBookingLiftcar = ""
    var dayBookingLiftcar = ""

    /**
     * 点击日期回调
     */
    fun onDateSetBookingLiftcar(view: DatePicker, year: Int, month: Int, day: Int) {
        this.yearBookingLiftcar = year.toString()
        this.monthBookingLiftcar = month.toString()
        this.dayBookingLiftcar = day.toString()
        val timePickerFragment = TimePickerFragment()
        timePickerFragment.clickOk = this::onTimeSetBookingLiftcar
        timePickerFragment.show(activityBookingLiftcar?.supportFragmentManager!!, "timePicker")
    }

    /**
     * 点击时间回调
     */
    fun onTimeSetBookingLiftcar(view: TimePicker, hourOfDay: Int, minute: Int) {
        BookingLiftcar[positionBookingLiftcar].value = FunctionUtils.formatTime(yearBookingLiftcar, monthBookingLiftcar, dayBookingLiftcar, hourOfDay, minute)
        BookingLiftcar[positionBookingLiftcar].id = FunctionUtils.formatTime(yearBookingLiftcar, monthBookingLiftcar, dayBookingLiftcar, hourOfDay, minute)
    }

    /**
     * 车型
     */
    fun setCardataBookingLiftcar(data: CarBrandParam) {
        BookingLiftcar[positionBookingLiftcar].value = data.brandname + "  " + data.seriesname + "  " + data.specname
        BookingLiftcar[positionBookingLiftcar].id = data.brand + "," + data.series + "," + data.spec
    }

    fun enableChangeDrivetime(){
        isdrivetime = 1
        if(!this.data.reserveid.equals("0") && this.data.reserveid.isNotEmpty() && canceldrive == 0){
            //2021-2-25 对是否有预约进行判断  有： 跟进、取消试驾、分配
            //修改预约时间  跟进级别、下次跟进时间可以选择， 跟进级别不能选择F级
            defaultViewData[11].isEnable = true
            defaultViewData[13].isEnable = true

            var levelList = ArrayList<DialogParam>()
            for (i in data.levelList) {
                if (!i.ikey.equals("F")) {
                    var item = DialogParam(i.title, i.ikey.toString())
                    item.ikey = i.ikey
                    levelList.add(item)
                }

            }

            defaultViewData[11].poplistdata = levelList
        }
    }
}